package com.zx.sdk.league.member;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.dm.sdk.ads.DMAdSdk;
import com.dm.sdk.ads.code.DMAdCloseType;
import com.dm.sdk.ads.config.DMAdConfig;
import com.dm.sdk.ads.interfaces.ad.DMRewardAdListener;
import com.dm.sdk.ads.interfaces.ad.DMSplashAdListener;
import com.dm.sdk.ads.interfaces.template.DMLoadTemplateAdListener;
import com.dm.sdk.ads.interfaces.template.DMTemplateAd;
import com.dm.sdk.common.config.DMConfig;
import com.dm.sdk.common.config.PermissionConfig;
import com.google.gson.Gson;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ReadyAdPosition;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.ConfigHelper;
import com.zx.sdk.util.LogHelper;
import com.zx.sdk.util.RunnableHelper;

import java.net.URLEncoder;
import java.util.HashMap;

import kotlin.text.Charsets;

public class DuoMeng extends BaseLeagueMember<DMTemplateAd, DMTemplateAd, Object, DMTemplateAd, Object> {

    @Override
    public String getName() {
        return "dm";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        if (!initialized) {
            //如果需要开启debug日志,可按如下配置:
            DMAdSdk.getInstance().onAppCreate((Application) context.getApplicationContext(), new DMConfig()
                    //日志开关,上线请删除这项配置或传入false
                    .debug(ZxSDK.isDebug())
                    .setPermission(new PermissionConfig() {
                        @Override
                        public boolean isCanGetLocation() {
                            return true;
                        }

                        @Override
                        public boolean isCanGetPhoneState() {
                            return true;
                        }

                        @Override
                        public boolean isCanGetAppList() {
                            return true;
                        }

                        @Override
                        public boolean isCanGetAndroidId() {
                            return true;
                        }

                        @Override
                        public boolean isCanGetOAID() {
                            return true;
                        }

                        @Nullable
                        @Override
                        public String getImei() {
                            return "";
                        }

                        @Nullable
                        @Override
                        public String getAndroidId() {
                            return "";
                        }

                        @Nullable
                        @Override
                        public String getOAID() {
                            if (ZxSDK.oaid != null && !ZxSDK.oaid.isEmpty()) {
                                return ZxSDK.oaid;
                            } else {
                                return ZxSDK.listener.getDeviceId();
                            }
                        }
                    }));
            DMAdSdk.getInstance().init(context);
        }
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        Context activity = container.getContext();
        if (!(activity instanceof Activity)) return;
        RunnableHelper.runOnUIThread(() -> {
            DMAdConfig config = new DMAdConfig()
                    .setTemplateViewSize(0, 0) //单位dp
                    .setCodeId(adInfo.getMapPid()); //广告位id
            DMAdSdk.getInstance().loadSplashAdTemplate((Activity) activity, config, new DMSplashAdListener() {
                @Override
                public void onLoadSuccess(DMTemplateAd ad) {
                    ad.startRender();
                }

                @Override
                public void onLoadFail(int code, String message) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY ->
                                listener.onPreLoadNoAD(DuoMeng.this, new ZxError(String.valueOf(code), message), adInfo);
                        case ZxSDK.FETCH_AND_SHOW ->
                                listener.onNoAD(DuoMeng.this, new ZxError(String.valueOf(code), message), adInfo);
                    }
                }

                @Override
                public void onRenderSuccess(DMTemplateAd ad) {
                    ad.setSplashAdListener(new DMTemplateAd.SplashAdListener() {
                        @Override
                        public void onAdShow() {
                            listener.onADExposure(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdClick() {
                            listener.onADClicked(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdClose(DMAdCloseType dmAdCloseType) {
                            listener.onADDismissed(DuoMeng.this, adInfo);
                        }
                    });
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY -> saveSplash(adInfo.getMapPid(), ad, container);
                        case ZxSDK.FETCH_AND_SHOW -> onShowSplash(adInfo, container, ad, listener);
                    }
                    listener.onADLoaded(DuoMeng.this, -1, adInfo);
                }

                @Override
                public void onRenderFail(int code, String msg) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY ->
                                listener.onPreLoadNoAD(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                        case ZxSDK.FETCH_AND_SHOW ->
                                listener.onNoAD(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                    }
                }
            });
        });
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable DMTemplateAd splash, BaseZxSplashListener listener) {
        if (splash != null) {
            splash.showSplashAd(container);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        RunnableHelper.runOnUIThread(() -> {
            String extra;
            try {
                extra = URLEncoder.encode(new Gson().toJson(adInfo), Charsets.UTF_8.displayName());
            } catch (Exception e) {
                extra = "";
            }
            DMAdConfig config = new DMAdConfig()
                    .setCodeId(adInfo.getMapPid()) //广告位id
                    .setRewardTime(ConfigHelper.getDmRewardTime())
                    .setThirdUserId(ZxSDK.getUid())
                    .setExtraData(extra);
            DMAdSdk.getInstance().loadRewardVideoAdTemplate(context, config, new DMRewardAdListener() {
                @Override
                public void onFailed(int code, String msg) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY ->
                                listener.onPreLoadADError(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                        case ZxSDK.FETCH_AND_SHOW ->
                                listener.onNoAD(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                    }
                }

                @Override
                public void onRenderFail(int code, String msg) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY ->
                                listener.onPreLoadADError(DuoMeng.this, new ZxError("-1", msg), adInfo);
                        case ZxSDK.FETCH_AND_SHOW ->
                                listener.onNoAD(DuoMeng.this, new ZxError("-1", msg), adInfo);
                    }
                }

                @Override
                public void onRenderSuccess(DMTemplateAd ad) {
                    ad.setRewardAdListener(new DMTemplateAd.RewardAdListener() {
                        private boolean isReward = false;

                        @Override
                        public void onAdShow() {
                            listener.onADExpose(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdClick() {
                            listener.onADClick(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdClose() {// 广告关闭,此时广告素材已经播放完成
                            listener.onADClose(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onVideoError() {//广告展示时出错
                            listener.onVideoPlayError(DuoMeng.this, new ZxError("-1", ""), adInfo);
                        }

                        @Override
                        public void onVideoComplete() {// 广告素材播放完成，视频未跳过，完整的播放了
                            if (!isReward) {
                                listener.onReward(DuoMeng.this, new HashMap<>(), adInfo);
                            }
                            listener.onVideoComplete(DuoMeng.this, adInfo);
                        }

                        /**
                         * 奖励发放
                         *
                         * @param isRewardValid 奖励是否有效，true 可以发放奖励。
                         * @param bundle        拓展参数，暂时为空
                         */
                        @Override
                        public void onRewardArrived(boolean isRewardValid, Bundle bundle) {
                            if (isRewardValid) {
                                isReward = true;
                                listener.onReward(DuoMeng.this, new HashMap<>(), adInfo);
                            }
                        }

                        @Override
                        public void onSkipVideo() {// 用户在观看时点击了跳过
                        }
                    });
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY -> saveReward(adInfo.getMapPid(), ad);
                        case ZxSDK.FETCH_AND_SHOW -> onShowReward(context, adInfo, ad, listener);
                    }
                    listener.onADLoad(DuoMeng.this, adInfo);
                }
            });
        });
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable DMTemplateAd reward, BaseZxRewardListener listener) {
        if (reward != null) {
            reward.showRewardVideoAd(context);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        RunnableHelper.runOnUIThread(() -> {
            DMAdConfig config = new DMAdConfig()
                    .setCodeId(adInfo.getMapPid()); //广告位id
            DMAdSdk.getInstance().loadInteractionAdTemplate(context, config, new DMLoadTemplateAdListener() {
                @Override
                public void onFailed(int code, String message) {
                    //广告请求失败
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY ->
                                listener.onPreLoadADError(DuoMeng.this, new ZxError(String.valueOf(code), message), adInfo);
                        case ZxSDK.FETCH_AND_SHOW ->
                                listener.onNoAD(DuoMeng.this, new ZxError(String.valueOf(code), message), adInfo);
                    }
                }

                @Override
                public void onSuccess(DMTemplateAd ad) {
                    LogHelper.d("dm onLoadInterstitial onSuccess");
                    ad.setTemplateAdListener(new DMTemplateAd.AdInteractionListener() {
                        @Override
                        public void onAdClose() {
                            //点击广告上的关闭按钮
                            listener.onADClose(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdClick() {//广告点击回调
                            listener.onADClick(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onAdShow() {//广告展示回调
                            listener.onADExpose(DuoMeng.this, adInfo);
                        }

                        @Override
                        public void onRenderFail(int code, String msg) {//广告渲染失败回调
                            switch (mode) {
                                case ZxSDK.FETCH_ONLY ->
                                        listener.onPreLoadADError(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                                case ZxSDK.FETCH_AND_SHOW ->
                                        listener.onNoAD(DuoMeng.this, new ZxError(String.valueOf(code), msg), adInfo);
                            }
                        }

                        @Override
                        public void onRenderSuccess() {//广告渲染成功回调
                            listener.onADLoad(DuoMeng.this, adInfo);
                            switch (mode) {
                                case ZxSDK.FETCH_ONLY -> saveInterstitial(adInfo.getMapPid(), ad);
                                case ZxSDK.FETCH_AND_SHOW ->
                                        onShowInterstitial(context, adInfo, ad, listener);
                            }
                        }
                    });
                    ad.startRender();
                }
            });
        });
    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable DMTemplateAd interstitial, BaseZxRewardListener listener) {
        if (interstitial != null) {
            interstitial.showInteractionAd(context);
            return true;
        }
        return false;
    }

    @Override
    public int getCpmByPid(String type, String pid) {
        int def = super.getCpmByPid(type, pid);
        switch (type) {
            case ZxSDK.SPLASH:
                def = splashMap.get(pid) == null ? def : (int) splashMap.get(pid).getBidPrice();
            case ZxSDK.REWARD:
                def = rewardMap.get(pid) == null ? def : (int) rewardMap.get(pid).getBidPrice();
            case ZxSDK.INTERSTITIAL:
                def = interstitialMap.get(pid) == null ? def : (int) interstitialMap.get(pid).getBidPrice();
        }
        cpmCache.put(type + pid, def);
        return def;
    }

    @Override
    public boolean isPreResReady(String type, String pid) {
        return switch (type) {
            case ZxSDK.SPLASH -> splashMap.get(pid) != null;
            case ZxSDK.REWARD -> rewardMap.get(pid) != null;
            case ZxSDK.INTERSTITIAL -> interstitialMap.get(pid) != null;
            default -> false;
        };
    }

    @Override
    public void notifyBiddingWin(String type, String mapPid, @Nullable ReadyAdPosition loser) throws Exception {
        DMTemplateAd iBidding = getIBidding(type, mapPid);
        if (iBidding == null) {
            return;
        }
        int cpm = (int) iBidding.getBidPrice();
        if (loser != null) {
            cpm = loser.getCpm();
        }
        iBidding.biddingSuccess(cpm);
        LogHelper.d(getName(), "notifyBiddingWin", mapPid);
    }

    @Nullable
    private DMTemplateAd getIBidding(String type, String pid) {
        DMTemplateAd iBidding = null;
        if (ZxSDK.REWARD.equals(type)) {
            iBidding = rewardMap.get(pid);
        } else if (ZxSDK.SPLASH.equals(type)) {
            iBidding = splashMap.get(pid);
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            iBidding = interstitialMap.get(pid);
        }
        return iBidding;
    }

    @Override
    public void notifyBiddingLose(String type, String mapPid, ReadyAdPosition winner, ZxSDK.LoseReason reason) throws Exception {

    }

    @Override
    public void destroySplash(Activity activity) {

    }

    @Override
    public void destroyShownSplash(Activity activity, DMTemplateAd splashAd) {

    }

    @Override
    public void destroyReward(Activity activity) {
    }

    @Override
    public void destroyShownReward(Activity activity, DMTemplateAd rewardAd) {

    }
}
